package com.simba.server.commands.impl.fetch;

import com.simba.common.command.ICommand;
import com.simba.common.database.DbOperator;
import com.simba.common.log.LogUtil;
import com.simba.server.components.data.PrinterInfo;
import org.apache.log4j.Logger;

import java.sql.ResultSet;
import java.util.List;

public class FetchPrinterInfoCmd implements ICommand
{
    public static final String NAME = "FetchPrinterInfoCmd";
    private final List<PrinterInfo> printerInfos;
    private final String sql = "select * from tt_printer_config;";
    private static final Logger logger = Logger.getLogger(FetchPrinterInfoCmd.class);
    public FetchPrinterInfoCmd(List<PrinterInfo> printerInfos)
    {
        this.printerInfos = printerInfos;
    }

    @Override public String getName()
    {
        return FetchPrinterInfoCmd.NAME;
    }

    @Override public Boolean run(Object params)
    {
        boolean ret = false;

        if (!(params instanceof DbOperator))
        {
            return ret;
        }

        try
        {
            DbOperator dbOperator = (DbOperator) params;
            dbOperator.prepareStatement(this.sql);
            ResultSet rs = dbOperator.executeQuery();

            while (rs.next())
            {
                PrinterInfo printerInfo = new PrinterInfo();

                printerInfo.setPrinterId(rs.getString("printerId"));
                printerInfo.setPrinterIp(rs.getString("printerIp"));
                printerInfo.setPrinterPort(rs.getInt("printerPort"));

                this.printerInfos.add(printerInfo);
            }

            ret = true;

        }
        catch (Exception ex)
        {
            ret = false;
            LogUtil.LogError(logger, "[FetchPrinterInfoCmd] fetch error! ");
        }

        return ret;
    }

}
